//
//  TransferRecordVC.swift
//  d11
//
//  Created by peale on 2018/7/27.
//  Copyright © 2018年 Tech_001. All rights reserved.
//
import UIKit
import MJRefresh
struct TransferType {
    public static let deposit = "存款历史"
    public static let withdraw = "取款历史"
    public static let transfer = "转账历史"
}

class TransferRecordVC:BXBaseVC,UITableViewDelegate,UITableViewDataSource{
    var requestPath: String?
    var index = 0
    var pageCount = 20
    var requestType: String?
    var loadingData = false
    var noMoreData = false
    
 //   var dataList: [[String:Any]]? = [[:]]
    var dataDict: [String : [[String:Any]]] = [:]
    var startDateTextField: SelectionTextField!
    var endDateTextField: SelectionTextField!
    let refreshFooter: MJRefreshFooter? = MJRefreshAutoNormalFooter()
    var keysArray : [String]? = [String]()
    let  reuseIdentifierHeadID : NSString = "TransferHeaderView"
    let  reuseIdentifierID : NSString = "TransferRecordCell"
    let  reuseIdentifierID2 : NSString = "TransferRecord2Cell"
    let  reuseIdentifierID3 : NSString = "TransferRecord3Cell"

    lazy var tableView:UITableView = {
        let table = UITableView(frame:CGRect(x: 0, y: 130 + kNavigationBarHeight, width: self.view.width, height:kScreenHeight-130-kTabBarBottom-kNavigationBarHeight), style:UITableView.Style.plain)
        table.dataSource = self
        table.delegate = self
        //table.layoutMargins = UIEdgeInsets.zero
        table.separatorStyle = .none
        table.backgroundColor  = UIColor.clear
        table.showsVerticalScrollIndicator = false
        table.tableFooterView = UIView.init()
        table.separatorStyle = .none
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.estimatedRowHeight = 0
        table.estimatedSectionHeaderHeight = 0
        table.estimatedSectionFooterHeight = 0
        if #available(iOS 11.0, *) {
            table.contentInsetAdjustmentBehavior = .never

        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        table.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: {
            self.pullToRefresh()
        })
        
        return table
    }()
    
    lazy var noDataLabel : UILabel = {
        let noLabel = UILabel.init(frame: CGRect(x: 0, y: 100, width: self.tableView.width, height:40))
        // noLabel.center = self.tableView.center
        noLabel.text =  "暂无记录"
        noLabel.isHidden = true
        noLabel.textAlignment = .center
        noLabel.textColor = HexRGBAlpha(0x666666,1)
        noLabel.font = UIFont.systemFont(ofSize: 15)
        self.tableView.addSubview(noLabel)
        return noLabel
    }()
    
   //刷新数据
    func pullToRefresh() -> Void {
        self.getRecordList()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if requestType == TransferType.deposit {
             self.title = TransferType.deposit
        }else if requestType  == TransferType.withdraw{
             self.title = TransferType.withdraw
        }else if requestType == TransferType.transfer{
            self.title = TransferType.transfer
        }
        self.view.backgroundColor = UIColor.white
        self.initHeadView()
        self.view.addSubview(self.tableView)
        self.dataDict.removeAll()
        self.getRecordList()
        
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
    }
    
    //初始化顶部视图
    func initHeadView() -> Void {
        //15 37.5 15 40 15
        //15 + 40
       let headBgView : UIView =  UIView.init()
        headBgView.backgroundColor = UIColor.white
        self.view.addSubview(headBgView)
        headBgView.snp.makeConstraints{(make) in
            make.top.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(130 + kNavigationBarHeight)
        }
        let centerLabel : UILabel =  UILabel.init()
        centerLabel.textAlignment = .center
        centerLabel.text = "至"
        centerLabel.textColor = HexRGBAlpha(0xA0A1A2,1)
        
        headBgView.addSubview(centerLabel)
        centerLabel.snp.makeConstraints{(make) in
            make.top.equalToSuperview().offset(kNavigationBarHeight + 15)
            make.width.equalTo(44)
            make.centerX.equalToSuperview()
            make.height.equalTo(37.5)
        }
        let leftView :UIView = UIView.init()
        leftView.backgroundColor = HexRGBAlpha(0xf1f2f3,1)
        headBgView.addSubview(leftView)
        leftView.snp.makeConstraints{(make) in
            make.top.equalToSuperview().offset(kNavigationBarHeight + 15)
            make.width.equalTo(0.7)
            make.right.equalTo(centerLabel.snp.left)
            make.height.equalTo(37.5)
        }
        
        let rightView :UIView = UIView.init()
        rightView.backgroundColor = HexRGBAlpha(0xf1f2f3,1)
        headBgView.addSubview(rightView)
        rightView.snp.makeConstraints{(make) in
            make.top.equalToSuperview().offset(kNavigationBarHeight + 15)
            make.width.equalTo(0.7)
            make.right.equalTo(centerLabel.snp.right)
            make.height.equalTo(37.5)
        }
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        
        self.startDateTextField = SelectionTextField()
        let cdate = Date()
        let startDate = cdate.adjust(.day, offset: -14)
   
       let dateStr = formatter.string(from: startDate)
        self.startDateTextField.placeholder = "开始日期"
        self.startDateTextField.text = dateStr
         self.startDateTextField.textAlignment = .center
        var dateStyle = DatePickerSetting()
        dateStyle.dateMode = .date
    //    dateStyle.date = startDate
        dateStyle.date = cdate
        dateStyle.maximumDate = cdate
        headBgView.addSubview(self.startDateTextField)
        self.startDateTextField.snp.makeConstraints{(make) in
            make.top.equalToSuperview().offset(15 + kNavigationBarHeight)
            make.width.equalTo(110)
            make.right.equalTo(leftView.snp.left)
            make.height.equalTo(37.5)
        }
        
        let formatter2 = DateFormatter()
        formatter2.dateFormat = "yyyy-MM-dd"
        self.endDateTextField = SelectionTextField()
        self.endDateTextField.placeholder = "结束日期"
        self.endDateTextField.text = formatter.string(from: cdate)
        self.endDateTextField.textAlignment = .center
        var dateStyle2 = DatePickerSetting()
        dateStyle2.dateMode = .date
        dateStyle2.date = cdate
        dateStyle2.maximumDate = cdate
        
        self.startDateTextField.showDatePicker("开始日期", datePickerSetting: dateStyle, autoSetSelectedText: false) { (textField, selectedDate) in
            let string = formatter.string(from: selectedDate)
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd"
           let sDate = formatter.date(from:string)
            let eDate = formatter.date(from:self.endDateTextField.text!)
            let components = NSCalendar.current.dateComponents([.day], from: sDate!, to: eDate!)
            print("时间\(components)")
            if  components.day != nil && components.day!+1 > 15 {
                 UIHelper.alertSimpleMessage(about: "", withDescription: "查询范围超过15天!", in: self)
            }else{
                textField.text = string
                self.startDateTextField.selectDate = selectedDate
            }
        //    self.endDateTextField.minmumDate = selectedDate
           
        }
        
        
      
        self.endDateTextField.showDatePicker("结束日期", datePickerSetting: dateStyle2, autoSetSelectedText: false) { (textField, selectedDate) in
            let string = formatter.string(from: selectedDate)
           
            let tempStartDate = formatter.date(from: self.startDateTextField.text!)
            if selectedDate.compare(tempStartDate!) == .orderedAscending
            {
                print("<")
                UIHelper.alertSimpleMessage(about: "", withDescription: "结束日期不能小于开始日期!", in: self)
                //  self.startDateTextField.text = string
            }else
            {
                let formatter = DateFormatter()
                formatter.dateFormat = "yyyy-MM-dd"
                let eDate = formatter.date(from:string)
                let sDate = formatter.date(from:self.startDateTextField.text!)
                let components = NSCalendar.current.dateComponents([.day], from: sDate!, to: eDate!)
                print("时间\(components)")
                if components.day != nil && components.day!+1 > 15 {
                    UIHelper.alertSimpleMessage(about: "", withDescription: "查询范围超过15天!", in: self)
                }else{
                    textField.text = string
                    self.endDateTextField.selectDate = selectedDate
                }
            
              //  self.startDateTextField.maxmumDate = selectedDate
            }
            
        }
        headBgView.addSubview(self.endDateTextField)
        self.endDateTextField.snp.makeConstraints{(make) in
            make.top.equalToSuperview().offset(15 + kNavigationBarHeight)
            make.width.equalTo(110)
            make.left.equalTo(rightView.snp.right)
            make.height.equalTo(37.5)
        }
       
        
        let searchBtn : UIButton  = UIButton.init(type: .custom)
        searchBtn.setTitle("搜索", for: .normal)
        let layerGradient = CAGradientLayer()
        layerGradient.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradient.frame = CGRect(x: 0, y: 0, width: kScreenWidth-100, height: 40)
        searchBtn.layer.addSublayer(layerGradient)
        searchBtn.layer.cornerRadius = 5;
        searchBtn.layer.masksToBounds = true
        searchBtn.addTarget(self, action: #selector(self.actionToSearch), for: .touchUpInside)
        headBgView.addSubview(searchBtn)
        searchBtn.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-100)
            make.height.equalTo(40)
            make.centerX.equalToSuperview()
            make.top.equalTo(centerLabel.snp.bottom).offset(15)
        }
    }
    //选择平台 : 50  top:20 height:30
    //搜索
    @objc func actionToSearch() -> Void {
        self.showLoadHUD(title: "")
        self.index = 0
        self.dataDict.removeAll()
        self.keysArray?.removeAll()
        self.tableView.mj_footer?.resetNoMoreData()
        self.getRecordList()
        if requestType == TransferType.deposit {
            ToolHelper.statisticsPage(pageName: "我的-存款历史-存款搜索")
        }else if requestType  == TransferType.withdraw{
            ToolHelper.statisticsPage(pageName: "我的-取款历史-取款搜索")
        }else if requestType == TransferType.transfer{
            ToolHelper.statisticsPage(pageName: "我的-转账历史-转账搜索")
        }
       
    }
    //获取数据
    func getRecordList() -> Void {
        var params =  [
            "offset": String(self.index),
            "pageCount": String(self.pageCount),
            "start": self.startDateTextField.text! + " 00:00:00",
            "end": self.endDateTextField.text! + " 23:59:59",
            ]
        self.noDataLabel.isHidden = true
        RequestHelper.post(atPath: self.requestPath!, withData: params, withCompletion: { data in
            do{
                let dataArray = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
                print("记录:\(dataArray)")
                let numToAdd = dataArray.count
                 DispatchQueue.main.async {
                     self.dismissLoadHUD()
                    self.index += numToAdd
                    for(_,value) in dataArray.enumerated(){
                     //   print("元素的索引是：\(index),元素值是：\(value)")
                          var tempValue = value;
                           var datenName = "created"
                           let datestr : String  =  tempValue[datenName] as! String
                           let datetime = Date(fromString:datestr, format: .custom("yyyy-MM-dd HH:mm:ss"))
                           let yearstr = datetime?.toString(format: .isoYear)
                           let monthDayStr = datetime?.toString(format: .custom("MM-dd"))
                            let timeStr = datetime?.toString(format: .custom("HH:mm:ss"))
                            tempValue["monthDay"] = monthDayStr
                            tempValue["showTime"] = timeStr
                            var array = self.dataDict[yearstr!]
                            if array == nil { //不存在 当前年份的数组则创建
                                var tempArr = [[String:Any]]() // 创建数组
                                tempArr.append(tempValue ) //添加条目
                                self.dataDict[yearstr!] = tempArr
                            }else
                            {
                                array?.append(tempValue)
                                self.dataDict[yearstr!] = array
                            }
                   //     }
                    }
//                    for (key, value) in self.dataDict {
//                        print("key: \(key), value: \(value)")
//                    }
                    //排序
                  self.keysArray = Array(self.dataDict.keys).sorted(by: { (num1 :String, num2:String) -> Bool in
                        return num1 > num2
                    })
                    print(self.keysArray as Any)
                    self.tableView.reloadData()
                    if numToAdd<self.pageCount{
                        if numToAdd <= 0&&self.index == 0{
                            self.noDataLabel.isHidden = false
                        }else{
                            self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                       
                    }else
                    {
                        if self.tableView.mj_footer?.isRefreshing == true{
                            self.tableView.mj_footer?.endRefreshing()
                        }
                    }
                }
              
            } catch {
                print(String(data: data, encoding: .utf8) as Any)
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    if self.tableView.mj_footer?.isRefreshing == true{
                        self.tableView.mj_footer?.endRefreshing()
                    }
                    UIHelper.alertSimpleMessage(about: "", withDescription: "取得资料时发生异常", in: self)
                }
            }

        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if self.tableView.mj_footer?.isRefreshing == true{
                    self.tableView.mj_footer?.endRefreshing()
                }
                UIHelper.alertSimpleMessage(about: "", withDescription: "取得资料时发生异常\(getErrorString())", in: self)
            }
        })
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return (self.keysArray?.count)!
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let keyYear = self.keysArray![section]
        let array = self.dataDict[keyYear]
        return array!.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if requestType == TransferType.transfer {
            return 95
        }
        return 125
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var headerView : TransferHeaderView? =  (tableView.dequeueReusableHeaderFooterView(withIdentifier: reuseIdentifierHeadID as String) as? TransferHeaderView)
        if headerView == nil {
            headerView = TransferHeaderView(reuseIdentifier: reuseIdentifierHeadID as String)
        }
        let title : String =  self.keysArray![section]
        headerView?.setData(title: title)
        return  headerView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if TransferType.deposit == requestType { //存款历史
            var cell :TransferRecordCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID as String) as? TransferRecordCell
            if cell == nil {
                cell =  TransferRecordCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID as String)
            }
            let keyYear = self.keysArray![indexPath.section]
            let array = self.dataDict[keyYear]
            var isShowMonthDay : Bool = true
            let currentDict  = array![indexPath.row]
            if indexPath.row != 0 {
                let lastDict  = array![indexPath.row-1]
                if currentDict["monthDay"] as? String ==  lastDict["monthDay"] as? String{
                    isShowMonthDay = false
                }
            }
            
            cell?.setData(dict: currentDict, isShowMonthDay: isShowMonthDay)
            return cell!
        }else if requestType == TransferType.withdraw{ //取款历史
            var cell :TransferRecord2Cell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID2 as String) as? TransferRecord2Cell
            if cell == nil {
                cell =   TransferRecord2Cell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID2 as String)
            }
            let keyYear = self.keysArray![indexPath.section]
            let array = self.dataDict[keyYear]
            var isShowMonthDay : Bool = true
            let currentDict  = array![indexPath.row]
            if indexPath.row != 0 {
                let lastDict  = array![indexPath.row-1]
                if currentDict["monthDay"] as? String ==  lastDict["monthDay"]  as? String{
                    isShowMonthDay = false
                }
            }
            
            cell?.setData(dict: currentDict, isShowMonthDay: isShowMonthDay)
            return cell!
        }else{ //转账/红利返水
            var cell :TransferRecord3Cell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID3 as String) as? TransferRecord3Cell
            if cell == nil {
                cell =  TransferRecord3Cell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID3 as String)
            }
            let keyYear = self.keysArray![indexPath.section]
            let array = self.dataDict[keyYear]
            var isShowMonthDay : Bool = true
            let currentDict  = array![indexPath.row]
            if indexPath.row != 0 {
                let lastDict  = array![indexPath.row-1]
                if currentDict["monthDay"]  as? String ==  lastDict["monthDay"]  as? String{
                    isShowMonthDay = false
                }
            }
        
            cell?.setData(dict: currentDict, isShowMonthDay: isShowMonthDay)
           
            return cell!
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let keyYear = self.keysArray![indexPath.section]
        let array = self.dataDict[keyYear]
        let currentDict  = array![indexPath.row]
        var title = "取款详情"
        if TransferType.transfer ==  self.requestType{
            title = (currentDict["outgpname"]  as? String)!
            PopWindowHelper.showTransferRecordPopView(title: title as NSString, msg: currentDict)
        }else{
            if TransferType.deposit == self.requestType {
                title = (currentDict["transtype"]  as? String)!
            }
            PopWindowHelper.showAmountRecordPopView(title: title as NSString, msg: currentDict)
        }
       
    }
    
}
